package com.dmgis.hndz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dmgis.hndz.common.utils.DateTime;
import com.dmgis.hndz.common.utils.FileUtil;
import com.dmgis.hndz.mapper.Ybba01cMapper;
import com.dmgis.hndz.pojo.*;
import com.dmgis.hndz.sddz.dto.Ybba01bDTO;
import com.dmgis.hndz.service.Ybba01cService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author PC
 * @description 针对表【ybba01c(市级预警产品表)】的数据库操作Service实现
 * @createDate 2024-01-30 23:28:00
 */
@Service
public class Ybba01cServiceImpl extends ServiceImpl<Ybba01cMapper, Ybba01c>
        implements Ybba01cService {


    @Qualifier("mongoPrimaryTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    @Value("${nginx.url}")
    private String nginxUrl;

    @Value("${nginx.filepath}")
    private String nginxFilepath;

    @Autowired
    private Ybba01cMapper ybba01cMapper;

    @Override
    public int FbProduct(Ybba02c ybba02c) {
        Ybba01c ybba01c = new Ybba01c();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ybba01c020", 2);
        queryWrapper.eq("ybba01c030", ybba02c.getYbba02c030());
        List<Ybba01c> list = baseMapper.selectList(queryWrapper);
        ybba01c.setYbba01c010(ybba02c.getYbba02c010());//id
        if (ybba02c.getYbba02c020().contains("短期")) {
            ybba01c.setYbba01c020(2);//产品类型 2代表短期 1代表短临
        } else {
            ybba01c.setYbba01c020(1);//产品类型 2代表短期 1代表短临
        }
        ybba01c.setYbba01c030(ybba02c.getYbba02c030());//时间
        String address2 = "";
        String address3 = "";
        String address4 = "";
        String address5 = "";
        String[] split1 = ybba02c.getYbba02c060().split(",");
        String[] split2 = ybba02c.getYbba02c070().split(",");//乡
        String[] split3 = ybba02c.getYbba02c100().split(",");//县
        for (int i = 0; i < split1.length; i++) {
            String city = split2[i];
            String county = split3[i];
            if ("风险极大".equals(split1[i])) {
                address5 = address5.contains(city) ? address5 + county + "、" : address5.length() > 0 ? address5.substring(0, address5.length() - 1) : address5 + (address5.equals("") ? "" : "，") + city + ":" + county + "、";
            } else if ("风险大".equals(split1[i])) {
                address4 = address4.contains(city) ? address4 + county + "、" : address4.length() > 0 ? address4.substring(0, address4.length() - 1) : address4 + (address4.equals("") ? "" : "，") + city + ":" + county + "、";
            } else if ("风险较大".equals(split1[i])) {
                address3 = address3.contains(city) ? address3 + county + "、" : address3.length() > 0 ? address3.substring(0, address3.length() - 1) : address3 + (address3.equals("") ? "" : "，") + city + ":" + county + "、";
            } else {
                address2 = address2.contains(city) ? address2 + county + "、" : address2.length() > 0 ? address2.substring(0, address2.length() - 1) : address2 + (address2.equals("") ? "" : "，") + city + ":" + county + "、";
            }
        }
        if (address5 != "") {
            ybba01c.setYbba01c070(address5);//一级预警区域
        }
        if (address4 != "") {
            ybba01c.setYbba01c060(address4);//二级预警区域
        }
        if (address3 != "") {
            ybba01c.setYbba01c050(address3);//三级预警区域
        }
        if (address2 != "") {
            ybba01c.setYbba01c040(address2);//四级预警区域
        }

        String targetPath = nginxFilepath + ybba02c.getYbba02c020() + ".docx";
        ybba01c.setYbba01c120(ybba02c.getYbba02c020() + ".docx");
        String maxid = baseMapper.selectMaxDocByType("2", ybba02c.getYbba02c090());
        if (ybba02c.getYbba02c020().contains("短临")) {
            maxid = baseMapper.selectMaxDocByType("1", ybba02c.getYbba02c090());
        }
        if (maxid == null || maxid == "") maxid = DateTime.now().toDateTimeString("yy") + "000";
        ybba01c.setYbba01c130(ybba02c.getYbba02c080());//预警坐标
        ybba01c.setYbba01c140(Integer.parseInt(maxid) + 1);//预警编号
        ybba01c.setYbba01c160(ybba02c.getYbba02c090());//行政编码

        int upcount = 0;
        if (list.size() == 0) {
            upcount = baseMapper.insert(ybba01c);
        } else {
            UpdateWrapper<Ybba01c> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("ybba01c010", ybba01c.getYbba01c010());
            upcount = baseMapper.update(ybba01c, updateWrapper);
        }


        if (upcount > 0) {
            byte[] byteArray = FileUtil.getBytesByFile(targetPath);
            //保存到mongodb库中
            HyDocFile hyDocFile = new HyDocFile();
            hyDocFile.setData(byteArray);
            hyDocFile.setTable_name("doc_warn_product_city_file");
            hyDocFile.setId(String.valueOf(ybba02c.getYbba02c010()));

            //先查询出来数据 这里的is(id)可以改成in(ids) 即为批量删除
            Query query = new Query(Criteria.where("id").is(hyDocFile.getId()));
            //再根据查询删除
            mongoTemplate.remove(query, hyDocFile.getClass());
            mongoTemplate.save(hyDocFile);

            byte[] byteArray1 = FileUtil.getBytesByFile(targetPath.replace(".docx", ".jpg"));
            //保存到mongodb库中
            HyImageFile hyimgFile = new HyImageFile();
            hyimgFile.setData(byteArray1);
            hyimgFile.setTable_name("short_warn_product_jpg_file");
            hyimgFile.setId(String.valueOf(ybba02c.getYbba02c010()));
            //先查询出来数据 这里的is(id)可以改成in(ids) 即为批量删除
            Query query2 = new Query(Criteria.where("id").is(hyimgFile.getId()));
            //再根据查询删除
            mongoTemplate.remove(query2, hyimgFile.getClass());
            mongoTemplate.save(hyimgFile);
            return 1;
        }
        return 0;
    }

    @Override
    public List<Ybba01bDTO> getYj(String startTime, String endTime, Integer yjLevel, String advcode) {
        List<Ybba01bDTO> ybba01bs = new ArrayList<>();
        List<Ybba01c> list = baseMapper.getYj(startTime, endTime, yjLevel, advcode);
        list.forEach(item -> {
            LocalDateTime ybba01c030 = item.getYbba01c030();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDate = ybba01c030.format(formatter);
            byte[] ybba01c130 = (byte[]) item.getYbba01c130();
            String encoded = new String(ybba01c130);
            Ybba01bDTO build = Ybba01bDTO.builder()
                    .ybba01b010(item.getYbba01c010())
                    .ybba01b020(item.getYbba01c020())
                    .ybba01b030(formattedDate)
                    .ybba01b040(item.getYbba01c040())
                    .ybba01b050(item.getYbba01c050())
                    .ybba01b060(item.getYbba01c060())
                    .ybba01b070(item.getYbba01c070())
                    .ybba01b080(item.getYbba01c080())
                    .ybba01b090(item.getYbba01c090())
                    .ybba01b100(item.getYbba01c100())
                    .ybba01b110(item.getYbba01c110())
                    .ybba01b120(item.getYbba01c120())
                    .ybba01b140(encoded)
                    .ybba01b150(item.getYbba01c140())
                    .ybba01b160(item.getYbba01c150())
                    .ybba01b170(item.getYbba01c160())
                    .ybba01b180(item.getYbba01c170())
                    .build();
            ybba01bs.add(build);
        });
        ybba01bs.sort(Comparator.comparing(Ybba01bDTO::getYbba01b030).reversed());
        return ybba01bs;
    }

    /**
     * 查询县级预警
     *
     * @param dateType 1：本年，2：本月，3：本日
     * @return
     */
    public List<Ybba01c> getYbba01cList(Integer dateType) {
        return ybba01cMapper.getYbba01cList(dateType);
    }
}




